<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\common\service\UploadFileService;
use think\facade\Log;
use think\response\Json;

class UploadFile extends Diluma
{
    /**
     * 图片上传
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UploadPicture(){
        $files = request()->file('file');
        if (!$files) {
            return json(['code'=>1, 'msg'=>'请选择要上传的文件']);
        }

//        $item = upload_oss_image($files, 'banner'); // 保存在阿里OSS
        $item = self::UpImages("banner");
        if (!empty($item)){
            return json(['code'=>0, 'msg'=>'上传成功', 'data'=>$item]);
        }else{
            return json(['code'=>1, 'msg'=>(string)$item]);
        }
    }

    /**
     * 缩略上传
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UploadThumb(){
        $files = request()->file('file');
        if (!$files) {
            return json(['code'=>1, 'msg'=>'请选择要上传的文件']);
        }
        $params = request()->param();
        $path = $params['path'] ?? 'thumb';
        $item = self::UpImages($path);
        if (!empty($item)){
            return json(['code'=>0, 'msg'=>'上传成功', 'data'=>$item]);
        } else{
            return json(['code'=>1, 'msg'=>(string)$item]);
        }
    }

    /**
     * 头像上传
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function UploadAvatar(){
        $item = self::UpImages("adminuser/avatar");
        if (is_array($item)){
            return json(['code'=>0, 'msg'=>'上传成功', 'data'=>$item]);
        }else{
            return json(['code'=>1, 'msg'=>(string)$item]);
        }
    }

    /**
     * 图片上传
     * @return Json
     */
    public function uploadPic(){
        $files = request()->file();
        if (!$files) {
            return json(['code'=>1, 'msg'=>'请选择要上传的文件']);
        }
        $params = request()->param();
        $path = $params['path'] ?? 'picture';
        $item = self::UpImages($path);
        if (!empty($item)){
            return json([
                'errno'=>0,
                'message'=>'上传成功',
                'data'=>[
                    'url' => $item['thumb_path'],
                    'alt' => $item['name'],
                    'href' => $item['thumb_path'] ?? $item['dir'],
                    'ext' => $item['ext'],
                    'original_name' => $item['original_name']
                 ]
            ]);
        } else{
            return json(['errno'=>1, 'message'=>(string)$item]);
        }
    }

    /**
     * 附件上传
     * @return Json
     */
    public function uploadAttachment(){
        $files = request()->file();
        if (!$files) {
            return json(['code'=>1, 'msg'=>'请选择要上传的文件']);
        }
        $params = request()->param();
        $path = $params['path'] ?? 'attachment';
        $item = UploadFileService::instance()
            ->setImageValidateArray(
                [
                    'fileExt'=>['mp3','mp4','doc','docx','xls','xls','txt','pdf','zip','rar'],
                    'fileMime' => ['audio/mpeg','video/mp4','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','text/plain','application/pdf','application/zip','application/octet-stream']
                ])
            ->setUploadPath($path)
            ->file();
        if (!empty($item) && $item['code'] == 0){
            return json([
                'code' => 0,
                'msg' => '上传成功',
                'data' => [
                    'url' => $item['dir'],
                    'name' => $item['name'],
                    'size' => $item['size'],
                    'type' => $item['type'],
                    'ext' => $item['ext'],
                    'original_name' => $item['original_name']
                ]
            ]);
        } else{
            return json(['code'=>$item['code'], 'msg'=>(string)$item['msg']]);
        }
    }

    /**
     * 公共图片上传方法
     * @param string $path  保存的路径
     * @param string $fileName input表单name
     * @param int $isSave  是否保存到数据库
     * @return Json
     * @author Diluma <1586498033@qq.com>
     * @date 2023/05/01
     */
    protected static function UpImages(string $path, string $fileName = "file", int $isSave = 1)
    {
        if (empty($path)) $path = "common/images";
        $item = UploadFileService::instance()
            ->setImageValidateArray(['fileExt'=>['jpg', 'jpeg', 'png', 'gif'], 'fileMime' => ['image/jpeg', 'image/gif', 'image/png']])
            ->setUploadPath($path)
            ->image($fileName);
//        if (is_array($item)){
//            if ($isSave==1){
//                AttachMent::attachmentAdd($res['name'],$res['size'],$res['type'],$res['dir'],$res['thumb_path'],$res['image_type'],$path,$res['ext']);
//            }
//        }
        return $item;
    }

    /**
     * 删除图片
     * @return Json
     */
    public function DeletePicture() {
        $param = request()->param();
        $path = $param['path'];
        if (!$path) {
            return json(['code'=>1, 'msg'=>'找不到该图片']);
        }
        $path = ltrim($path, '/');
        $path = rtrim($path, ';');
        if (file_exists($path)) {
            unlink($path);
            return json(['code'=>0, 'msg'=>'删除成功']);
        } else {
            Log::error("file not exists, file: {$path}");
            return json(['code'=>1, 'msg'=>'图片不存在']);
        }
    }
}